<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="发起时间" prop="useTime" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_commit_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['humanresource:hrEmployeeChangeApply:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['humanresource:hrEmployeeChangeApply:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['humanresource:hrEmployeeChangeApply:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['humanresource:hrEmployeeChangeApply:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="hrEmployeeChangeApplyList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="发起人" align="center" prop="initialId" fixed="left">
          <template #default="scope">
            <span>{{ scope.row.initialName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="deptId" fixed="left">
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发起时间" align="center" prop="initialTime" width="120" fixed="left">
          <template #default="scope">
            <span>{{ parseTime(scope.row.initialTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="性别" align="center" prop="sex" :formatter="formatSex"/>
        <el-table-column label="入职时间" align="center" prop="onboardTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.onboardTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="原部门" align="center" prop="originalDeptName" >
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.originalDeptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="原项目" align="center" prop="originalProjectName" >
          <template #default="scope">
            <el-tooltip :content="scope.row.originalProjectName" placement="top" :disabled="!scope.row.originalProjectName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.originalProjectName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="原职位" align="center" prop="originalPosition" >
          <template #default="scope">
            <el-tooltip :content="scope.row.originalPosition" placement="top" :disabled="!scope.row.originalPosition">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.originalPosition }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="新部门" align="center" prop="newDeptId" >
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.newDeptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="新项目" align="center" prop="newProjectName" >
          <template #default="scope">
            <el-tooltip :content="scope.row.newProjectName" placement="top" :disabled="!scope.row.newProjectName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.newProjectName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="新职位" align="center" prop="newPosition" >
          <template #default="scope">
            <el-tooltip :content="scope.row.newPosition" placement="top" :disabled="!scope.row.newPosition">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.newPosition }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="调动后薪资" align="center" prop="salaryDisplay" width="100">
          <template #default="scope">
            <el-tooltip
              :content="scope.row.salaryDisplay"
              placement="top"
              :disabled="!scope.row.salaryDisplay"
            >
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;"
                >
                  {{ scope.row.salaryDisplay }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="异动类型" align="center" prop="changeType" >
           <template #default="scope">
            <el-tooltip :content="scope.row.changeType" placement="top" :disabled="!scope.row.changeType">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.changeType }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="120" fixed="right">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status" fixed="right">
          <template #default="scope">
            <dict-tag :options="approval_commit_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="110">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['humanresource:hrEmployeeChangeApply:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['humanresource:hrEmployeeChangeApply:remove']"></el-button>
            </el-tooltip>
            <!-- 审批按钮 -->
            <el-tooltip content="提交审批" placement="top">
              <el-button
                link
                type="primary"
                icon="DocumentChecked"
                @click="openApprovalFlow(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改员工异动申请审批对话框 -->
    <el-dialog 
      :title="dialog.title" 
      v-model="dialog.visible" 
      width="900px" 
      append-to-body
    >
      <template #default>
        <el-form ref="hrEmployeeChangeApplyFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
          <el-row :gutter="20"> 
            <el-col :span="24">
              <el-form-item label="发起人" prop="initialName">
                <el-input v-model="form.initialName" placeholder="请输入发起人名称" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="部门" prop="deptId">
                  <el-tree-select
                    v-model="form.deptId"
                    :data="deptTree"
                    placeholder="请选择申请部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                  />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发起时间" prop="initialTime">
                <el-date-picker clearable
                  v-model="form.initialTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择发起时间"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="form.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex" required>
                <el-select
                  v-model="form.sex"
                  placeholder="请选择性别"
                  style="width: 100%;"
                >
                  <el-option label="男" :value="1" />
                  <el-option label="女" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="入职时间" prop="onboardTime">
                <el-date-picker clearable
                  v-model="form.onboardTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择入职时间"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <!-- 原部门 -->
            <el-col :span="12">
              <el-form-item label="原部门" prop="originalDeptId">
                <el-tree-select
                  v-model="form.originalDeptId"
                  :data="deptTree"
                  placeholder="请选择原部门"
                  :props="{ label: 'label', value: 'id', children: 'children' }"
                  check-strictly
                  filterable
                  :default-expand-all="true"
                  style="width: 100%"
                  @visible-change="handleVisibleChange"
                  @change="id => handleDeptChange('original', id)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="原职位" prop="originalPosition">
                <el-input v-model="form.originalPosition" placeholder="请输入原职位" />
              </el-form-item>
            </el-col>
            <!-- 原项目 -->
            <el-col :span="24">
              <el-form-item label="原项目" prop="originalProjectIdArray">
                <el-select
                  :key="projectSelectKey['original']"
                  v-model="form.originalProjectIdArray"
                  multiple
                  placeholder="请输入原项目名称搜索"
                  clearable
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="q => searchProjects('original', q)"
                  :loading="state.original.loading"
                  style="width: 100%"
                  @change="val => handleProjectChange('original', val)"
                >
                  <el-option
                    v-for="p in originalProjectList"
                    :key="p.id"
                    :label="`${p.proName} (${p.proNumber || ''})`"
                    :value="String(p.id)"
                  />
                  <template #empty>
                    <div class="text-center p-2">
                      <span v-if="state.original.loading">加载中...</span>
                      <span v-else-if="state.original.keyword && originalProjectList.length === 0">未找到相关项目</span>
                      <span v-else>请输入项目名称进行搜索</span>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 新部门 -->
            <el-col :span="12">
              <el-form-item label="新部门" prop="newDeptId">
                <el-tree-select
                  v-model="form.newDeptId"
                  :data="deptTree"
                  placeholder="请选择新部门"
                  :props="{ label: 'label', value: 'id', children: 'children' }"
                  check-strictly
                  filterable
                  :default-expand-all="true"
                  style="width: 100%"
                  @visible-change="handleVisibleChange"
                  @change="id => handleDeptChange('new', id)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="新职位" prop="newPosition">
                <el-input v-model="form.newPosition" placeholder="请输入新职位" />
              </el-form-item>
            </el-col>
            <!-- 新项目 -->
            <el-col :span="24">
              <el-form-item label="新项目" prop="newProjectIdArray">
                <el-select
                  :key="projectSelectKey['new']"
                  v-model="form.newProjectIdArray"
                  multiple
                  placeholder="请输入新项目名称搜索"
                  clearable
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="q => searchProjects('new', q)"
                  :loading="state.new.loading"
                  style="width: 100%"
                  @change="val => handleProjectChange('new', val)"
                >
                  <el-option
                    v-for="p in newProjectList"
                    :key="p.id"
                    :label="`${p.proName} (${p.proNumber || ''})`"
                    :value="String(p.id)"
                  />
                  <template #empty>
                    <div class="text-center p-2">
                      <span v-if="state.new.loading">加载中...</span>
                      <span v-else-if="state.new.keyword && newProjectList.length === 0">未找到相关项目</span>
                      <span v-else>请输入项目名称进行搜索</span>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="调动后薪资" prop="salaryRecords">
                <div v-for="(item, index) in form.salaryRecords" :key="index" style="display:flex; gap:8px; align-items:center; margin-bottom:8px;">
                  <!-- 阶段 -->
                  <el-select v-model="item.salaryType" placeholder="请选择阶段" style="flex:0 0 120px;">
                    <el-option label="实习期" value="实习期" />
                    <el-option label="试用期" value="试用期" />
                    <el-option label="转正" value="转正" />
                  </el-select>
                  <!-- 税前/税后 -->
                  <el-select v-model="item.salaryTaxType" placeholder="税前/税后" style="flex:0 0 120px;">
                    <el-option label="税前" value="税前" />
                    <el-option label="税后" value="税后" />
                  </el-select>
                  <!-- 金额 -->
                  <el-input v-model="item.salaryAmount" placeholder="请输入工资金额(元/月)" style="flex:1;" />
                  <!-- 删除按钮 -->
                  <el-button type="danger" icon="el-icon-delete" @click="removeRecord(index)" link>删除</el-button>
                </div>
                <div>
                  <!-- 新增按钮 --> 
                  <el-button style="margin-bottom: 9px;" type="primary" icon="el-icon-plus" @click="addRecord" link>新增</el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="异动类型" prop="changeType">
                <el-select
                  v-model="form.changeType"
                  placeholder="请选择异动类型"
                  @change="handleTypeChange"
                  filterable
                  style="width: 100%;"
                >
                  <el-option label="晋升" value="晋升" />
                  <el-option label="降职" value="降职" />
                  <el-option label="轮岗" value="轮岗" />
                  <el-option label="调动" value="调动" />
                  <el-option label="晋级" value="晋级" />
                  <el-option label="降级" value="降级" />
                  <el-option label="临时借调" value="临时借调" />
                  <el-option label="待岗" value="待岗" />
                  <el-option label="其他" value="其他" />
                </el-select>
                <el-dialog
                  title="请输入其他增补类型"
                  :model-value="showOtherDialog"
                  @update:model-value="val => showOtherDialog = val"
                  width="400px"
                  :close-on-click-modal="false"
                  custom-class="other-dialog"
                  center
                >
                  <div class="dialog-content">
                    <el-input
                      v-model="tempOtherType"
                      placeholder="请输入其他类型"
                      clearable
                      style="width: 100%;"
                      @keyup.enter="confirmOther"
                    />
                  </div>
                  <template #footer>
                    <div class="dialog-footer-center">
                      <el-button @click="cancelOther">取消</el-button>
                      <el-button type="primary" @click="confirmOther">确认</el-button>
                    </div>
                  </template>
                </el-dialog>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核流程配置对话框 --> 
    <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="'HR-MOBILITY-CHANGE-AUDIT'"
      :business-id="auditIdForApproval" :key="auditIdForApproval" title="配置人员异动申请审核流程" @confirm="handleApprovalConfirm"
      @cancel="handleApprovalCancel" />
  </div>
</template>

<script setup name="HrEmployeeChangeApply" lang="ts">
import { listHrEmployeeChangeApply, getHrEmployeeChangeApply, delHrEmployeeChangeApply, addHrEmployeeChangeApply, updateHrEmployeeChangeApply } from '@/api/general/humanresources/mobility/change/index';
import { HrEmployeeChangeApplyVO, HrEmployeeChangeApplyQuery, HrEmployeeChangeApplyForm } from '@/api/general/humanresources/mobility/change/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';
import { ItemTreeNode } from '@/api/project/init/contract/types';
import { listProContract } from '@/api/project/init/contract';
import { getProInfo, pageListProInfo, pageListForQuery } from '@/api/project/init/proInfo';
import { resetApprovalStatus } from '@/components/ApprovalFlow/api';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const hrEmployeeChangeApplyList = ref<HrEmployeeChangeApplyVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 用户信息
const userStore = useUserStore();

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 初始化项目下拉框
const projectTree = ref<ItemTreeNode[]>([]);

// 引入数据字典
const { adm_item_type, approval_commit_status } = toRefs<any>(proxy?.useDict('adm_item_type', 'approval_commit_status'));

// 提交审核相关
const approvalFlowVisible = ref(false);
const currentSubmitAuditRow = ref<any>(null);
const auditIdForApproval = ref<string | number | undefined>(undefined);
const originalProjectList = ref<ProInfoVO[]>([]);
const newProjectList = ref<ProInfoVO[]>([]);
// 强制刷新 select
const projectSelectKey = ref({ original: 0, new: 0 });

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

// 是否选择“其他”类型
const otherType = ref('')      // 用户手输的“其他”类型
const isOther = ref(false)     // 是否选择“其他”
const showOtherDialog = ref(false); // 控制弹窗显示
const tempOtherType = ref("");       // 弹窗临时输入

const queryFormRef = ref<ElFormInstance>();
const hrEmployeeChangeApplyFormRef = ref<ElFormInstance>();

// 状态池（原 / 新）
const state = ref({
  original: {
    list: [] as any[],
    loading: false,
    keyword: '',
    backfillDone: false,
    timer: null as number | null,
    reqId: 0
  },
  new: {
    list: [] as any[],
    loading: false,
    keyword: '',
    backfillDone: false,
    timer: null as number | null,
    reqId: 0
  }
})
// 定义需要触发必填校验的部门名称或 ID
const requiredProjectDepts = ["董办", "综合办", "财务中心","商务中心"];

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 性别映射
const sexMap = {
  0: '女',
  1: '男'
};

const formatSex = (row, column, cellValue) => {
  return sexMap[cellValue] || '';
};

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: HrEmployeeChangeApplyForm = {
  id: undefined,
  initialId: userStore.userId,
  initialName: userStore.name,
  deptId: userStore.deptId,
  deptName: userStore.deptName,
  initialTime: formatLocalDate(),
  name: undefined,
  sex: undefined,
  onboardTime: undefined,
  originalDeptId: undefined,
  originalDeptName: undefined,
  originalProjectIdArray: [] as string[],
  originalProjectId: undefined,
  originalProjectName: undefined,
  originalPosition: undefined,
  newDeptId: undefined,
  newDeptName: undefined,
  newProjectIdArray: [] as string[],
  newProjectId: undefined,
  newProjectName: undefined,
  newPosition: undefined,
  salary: undefined,
  salaryRecords: [],
  changeType: undefined,
  status: undefined,
}
const data = reactive<PageData<HrEmployeeChangeApplyForm, HrEmployeeChangeApplyQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    initialId: undefined,
    deptId: undefined,
    initialTime: undefined,
    name: undefined,
    sex: undefined,
    onboardTime: undefined,
    originalDeptId: undefined,
    originalProjectId: undefined,
    originalPosition: undefined,
    newDeptId: undefined,
    newProjectId: undefined,
    newPosition: undefined,
    salary: undefined,
    changeType: undefined,
    status: undefined,
    createTime: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    initialName: [{ required: true, message: "请输入发起人", trigger: "blur" }],
    deptId: [{ required: true, message: "请选择申请部门", trigger: "change" }],
    initialTime: [{ required: true, message: "请选择发起时间", trigger: "change" }],
    name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    sex: [{ required: true, message: "请选择性别", trigger: "change" }],
    onboardTime: [{ required: true, message: "请选择入职时间", trigger: "change" }],
    originalDeptId: [{ required: true, message: "请选择原部门", trigger: "change" }],
    originalProjectId: [
      {
        validator: (rule, value, callback) => {
          if (form.value.originalDeptId && value === null) {
            callback(new Error("原项目填写后必须选择新项目"));
          } else {
            callback();
          }
        },
        trigger: "change",
      },
    ],
    originalPosition: [{ required: true, message: "请输入原职位", trigger: "blur" }],
    newDeptId: [{ required: true, message: "请选择新部门", trigger: "change" }],
    newProjectId: [
      {
        validator: (rule, value, callback) => {
          if (form.value.originalProjectId && !value) {
            callback(new Error("原项目填写后，新项目必填"));
          } else {
            callback();
          }
        },
        trigger: "change",
      },
    ],
    newPosition: [{ required: true, message: "请输入新职位", trigger: "blur" }],
    salaryRecords: [
      {
        validator: (rule, value, callback) => {
          if (!value || !value.length) {
            callback(new Error("请填写调动后薪资"));
          } else {
            for (let i = 0; i < value.length; i++) {
              const rec = value[i];
              if (!rec.salaryType) return callback(new Error(`第${i + 1}条薪资阶段不能为空`));
              if (!rec.salaryTaxType) return callback(new Error(`第${i + 1}条税前/税后不能为空`));
              if (!rec.salaryAmount) return callback(new Error(`第${i + 1}条金额不能为空`));
            }
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    changeType: [{ required: true, message: "请选择异动类型", trigger: "change" }],
    }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询员工异动申请审批列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listHrEmployeeChangeApply(queryParams.value);
    hrEmployeeChangeApplyList.value = res.rows.map((item: any) => {
      const newItem = { ...item };
      // 解析 salary 字段为数组
      let salaryArr: any[] = [];
      try {
        salaryArr = typeof item.salary === 'string' ? JSON.parse(item.salary) : [];
      } catch (err) {
        salaryArr = [];
      }
      // 转成显示字符串
      newItem.salaryDisplay = salaryArr
        .map(s => `${s.salaryType || '-'}（${s.salaryTaxType || '-'}）：${s.salaryAmount || '-'}`)
        .join('；');
      // attachments 同理，如果需要展示可转
      try {
        newItem.attachments = typeof item.attachmentName === 'string' ? JSON.parse(item.attachmentName) : [];
      } catch (err) {
        newItem.attachments = [];
      }
      return newItem;
    });
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  form.value.salaryRecords = [];
  hrEmployeeChangeApplyFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: HrEmployeeChangeApplyVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加员工异动申请审批";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: HrEmployeeChangeApplyVO) => {
  if (row.status != 4) {
    ElMessage.error("只能对审核不过的申请进行修改")
    return;
  }
  reset(); // 重置表单状态
  const _id = row?.id || ids.value[0]; // 优先使用传入 row 的 id
  const res = await getHrEmployeeChangeApply(_id); // 获取后台数据
  const data = { ...res.data };
  // salary -> salaryRecords
  if (data.salary) {
    try {
      data.salaryRecords = JSON.parse(data.salary);
    } catch (e) {
      console.warn("salary 字段解析失败", e);
      data.salaryRecords = [];
    }
  }
  // 回显项目（字符串 v-model 方案）
  if (data.originalProjectId) await backfillProjectList(data.originalProjectId, 'original');
  if (data.newProjectId) await backfillProjectList(data.newProjectId, 'new');
  // 将后台数据赋值给表单
  Object.assign(form.value, data);
  // 如果有原项目ID且新项目ID为空，可以选择清空或保持不变
  if (form.value.originalProjectId && !form.value.newProjectId) {
    form.value.newProjectId = null; // 或保持不变
  }
  // 弹窗显示
  dialog.visible = true;
  dialog.title = "修改员工异动申请审批";
};

/**
 * 补全项目数据，仅用于已有 projectId 时的回显
 */
async function backfillProjectList(projectId: string | string[], type: 'original' | 'new') {
  try {
    const ids = Array.isArray(projectId)
      ? projectId
      : projectId.toString().split(',').map(id => id.trim()).filter(Boolean);

    console.log(`[backfillProjectList:${type}] 待补全项目 ID 列表:`, ids);

    const projectPromises = ids.map(id => getProInfo(Number(id)));
    const projectData = await Promise.all(projectPromises);

    // 根据 type 选择对应 projectList
    const list = type === 'original' ? originalProjectList.value : newProjectList.value;

    projectData.forEach(res => {
      if (res?.data && !list.some(p => String(p.id) === String(res.data.id))) {
        list.push({
          id: String(res.data.id),
          proName: res.data.proName,
          proNumber: res.data.proNumber,
          contractId: 0,
          contractName: '',
          projectRegion: '',
          proType: '',
          proContent: '',
          proPresidentsId: '',
          proLeadersId: '',
          ownerUnit: '',
          proAmount: null,
          proAmountRemark: '',
          proStatus: '',
          remark: '',
          createTime: '',
          createBy: ''
        });
        console.log(`[backfillProjectList:${type}] 补全加入 projectList:`, list[list.length - 1]);
      }
    });

    await nextTick();
    form.value[`${type}ProjectIdArray`] = ids.map(String);

    // 强制刷新 select
    projectSelectKey.value[type]++;
    console.log(`[backfillProjectList:${type}] 回显完成, projectIdArray:`, form.value[`${type}ProjectIdArray`]);
  } catch (error) {
    console.error(`[backfillProjectList:${type}] 项目补全失败:`, error);
  }
}



/** 提交按钮 */
const submitForm = () => {
  hrEmployeeChangeApplyFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true; // ✅ 先置为 true
       // 自定义逻辑校验
      if (form.value.originalDeptId && form.value.newDeptId && form.value.originalDeptId === form.value.newDeptId) {
        ElMessage.warning("原部门不能与新部门相同");
        return;
      }

      if (form.value.originalProjectId && form.value.newProjectId && form.value.originalProjectId === form.value.newProjectId) {
        ElMessage.warning("原项目不能与新项目相同");
        return;
      }
      const submitData = { ...form.value };
      // 部门字段保持单值（不需要 join）
      submitData.originalDeptId = form.value.originalDeptId;
      submitData.newDeptId = form.value.newDeptId;
      // ✅ 多选项目转字符串提交
      submitData.originalProjectId = form.value.originalProjectIdArray?.join(',') || '';
      submitData.newProjectId = form.value.newProjectIdArray?.join(',') || '';
      if (Array.isArray(submitData.salaryRecords)) {
        submitData.salary = JSON.stringify(submitData.salaryRecords);
      }
        if (form.value.id) {
          await updateHrEmployeeChangeApply(submitData);
          // 调用重置审核流程接口
          await resetApprovalStatus('HR-MOBILITY-CHANGE-AUDIT', Number(form.value.id), '不可审核')
        } else {
          const res = await addHrEmployeeChangeApply(submitData);
          // 触发审核流程配置对话框
          auditIdForApproval.value = res.data;
          approvalFlowVisible.value = true;
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: HrEmployeeChangeApplyVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除员工异动申请审批编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delHrEmployeeChangeApply(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('humanresource/hrEmployeeChangeApply/export', {
    ...queryParams.value
  }, `hrEmployeeChangeApply_${new Date().getTime()}.xlsx`)
}

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
       tree?.expandAll?.();
    }, 0);
  }
};

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

/** 
 * 通用：项目选择变化
 * @param type 'original' | 'new'  —— 用于区分原/新
 * @param selectedIds 当前选中的项目 id（单选或多选）
 */
const handleProjectChange = (type: 'original' | 'new', selectedIds: string[] | number[] | string | number) => {
  const ids = Array.isArray(selectedIds) ? selectedIds : [selectedIds];
  const findNodeById = (nodes: any[], id: string | number): any => {
    for (const node of nodes) {
      if (node.id === id) return node;
      if (node.children) {
        const found = findNodeById(node.children, id);
        if (found) return found;
      }
    }
    return null;
  };
  const found = ids.map(id => findNodeById(projectTree.value, id)).filter(Boolean);
  form.value[`${type}ProjectName`] = found.map(p => p.contractName).join('，');
  console.log(`[handleProjectChange:${type}]`, form.value[`${type}ProjectName`]);
};

// 新增一条薪资记录，最多 3 条
const addRecord = () => {
  if (form.value.salaryRecords.length >= 3) {
    ElMessage.warning('最多只能添加 3 条薪资记录');
    return;
  }
  form.value.salaryRecords.push({ salaryType: null, salaryTaxType: null, salaryAmount: null });
};

// 删除一条薪资记录，至少保留 1 条
const removeRecord = (index: number) => {
  if (form.value.salaryRecords.length <= 1) {
    ElMessage.warning('至少保留一条薪资记录');
    return;
  }
  form.value.salaryRecords.splice(index, 1);
};

// 将最终选择值更新到 form.type
watch(otherType, (val) => {
  if (isOther.value) {
    form.value.changeType = val
  }
})

// 选择变化处理
const handleTypeChange = (val) => {
  if (val === "其他") {
    // 如果已经有值，弹窗显示当前值
    tempOtherType.value = otherType.value || "";
    showOtherDialog.value = true;
  } else {
    // 如果取消选择“其他”，清空手动输入值
    otherType.value = "";
  }
};

// 弹窗取消
const cancelOther = () => {
  showOtherDialog.value = false;
  form.value.changeType = ""; // 取消“其他”，清空原下拉值
};

// 弹窗确认
const confirmOther = () => {
  otherType.value = tempOtherType.value;
  form.value.changeType = otherType.value; // 显示在原下拉框
  showOtherDialog.value = false;
};

// 通用：树节点查找
function findNodeById(tree: any[], id: string | number): any {
  for (const node of tree) {
    if (node.id === id) return node
    if (node.children) {
      const found = findNodeById(node.children, id)
      if (found) return found
    }
  }
  return null
}

// 通用：部门变化
function handleDeptChange(type: 'original' | 'new', id: string | number) {
  const node = findNodeById(deptTree.value, id)
  if (!node) return
  console.log(`[handleDeptChange:${type}]`, node.label)

  if (requiredProjectDepts.includes(node.label)) {
    searchProjects(type, node.label, true)
  } else {
    form.value[`${type}ProjectIdArray`] = []
    state.value[type].list = []
  }
}

// 通用：防抖搜索
function searchProjects(type: 'original' | 'new', keyword: string, deptTrigger = false) {
  const s = state.value[type]
  s.keyword = keyword
  if (s.timer) clearTimeout(s.timer)
  s.timer = window.setTimeout(() => getProjectList(type, keyword, deptTrigger), 300)
}

// 通用：获取项目列表 + 回显补全
async function getProjectList(type: 'original' | 'new', keyword = '', deptTrigger = false) {
  const s = state.value[type]
  try {
    s.loading = true
    const reqId = ++s.reqId
    const res = await pageListForQuery({ pageNum: 1, pageSize: 50, flowStatus: '3', proName: keyword || undefined })
    if (reqId !== s.reqId) return

    s.list = res.rows || []
    console.log(`[getProjectList:${type}]`, s.list.length, '条')

    const arrKey = `${type}ProjectIdArray` as 'originalProjectIdArray' | 'newProjectIdArray'
    if (deptTrigger) {
      form.value[arrKey] = s.list.map(p => String(p.id))
      // 刷新 select
      projectSelectKey.value[type]++;
    } else if (!s.backfillDone && form.value[arrKey]?.length) {
      const missing = form.value[arrKey].filter(id => !s.list.some(p => String(p.id) === id))
      if (missing.length > 0) {
        s.backfillDone = true
        const details = await Promise.all(missing.map(id => getProInfo(Number(id))))
        details.forEach(r => {
          if (r?.data && !s.list.some(p => p.id === r.data.id)) {
            s.list.push({ id: r.data.id, proName: r.data.proName, proNumber: r.data.proNumber })
          }
        })
        form.value[arrKey] = [...form.value[arrKey]]
      } else {
        s.backfillDone = true
      }
    }
  } catch (err) {
    console.error(`[getProjectList:${type}]`, err)
    ElMessage.error('获取项目列表失败')
  } finally {
    s.loading = false
  }
}

/** 审核流程确认回调 */
const handleApprovalConfirm = async () => {
  try {
    ElMessage.success('工作日志审核流程提交成功');
    approvalFlowVisible.value = false;
    currentSubmitAuditRow.value = null;
    auditIdForApproval.value = undefined;
  } catch (error) {
    console.error('审核流程提交失败:', error);
    ElMessage.error('审核流程提交失败');
  }
};

/** 审核流程取消回调 */
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentSubmitAuditRow.value = null;
  auditIdForApproval.value = undefined;
  // 审核流程取消时，表单已经在submitCurrentWorklogs中重置了，这里不需要重复重置
};

// 打开审批弹窗
const openApprovalFlow = (row?: HrEmployeeChangeApplyVO) => {
  if (row.status != 5){
    ElMessage.error('只能提交已导入的信息审批！');
    return;
  }
  auditIdForApproval.value = row.id;
  approvalFlowVisible.value = true;
};

onMounted(() => {
  getList();
  fetchDeptTree();
});
</script>
